<?php
namespace Demo\App\Handler;

use Swork\Bean\Annotation\Inject;
use Swork\Bean\BeanCollector;
use Swork\Behavior\RequestInterface;
use Swork\Client\Amqp;
use Swork\Helper\DateHelper;
use Swork\Helper\IdHelper;
use Swork\Server\Http\Argument;
use Swork\Server\Tasker;

class RequestHandler extends BeanCollector implements RequestInterface
{
    /**
     * @Inject("amqp_common_task")
     * @var Amqp
     */
    private $amqp;

    /**
     * 请求开始处理
     * @param string $uri 请求地址
     * @param Argument $argument
     * @return string|bool 请求的KEY，md5(uri + get + stime + rand)
     */
    public function begin(string $uri, Argument $argument)
    {
        //外部参数
        $time = DateHelper::getTime();
        $gets = $argument->get();
        $rand = IdHelper::generate();

        //投递任务
        Tasker::deliver(static::class, 'recordBegin', [$uri, $gets, $time]);

        //返回KEY
        return md5($uri . $time . json_encode($gets, JSON_UNESCAPED_UNICODE) . $rand);
    }

    /**
     * @param string $key 请求的KEY，从begin中来
     * @param Argument $argument
     * @param mixed $result 处理结果
     * @return mixed
     */
    public function end(string $key, Argument $argument, $result)
    {
        //外部参数
        $time = DateHelper::getTime();

        //投递任务
        Tasker::deliver(static::class, 'recordEnd', [$key, $time]);
    }

    /**
     * 记录投递的任务
     * @param string $uri
     * @param array $gets
     * @param float $time
     */
    public function recordBegin(string $uri, array $gets, float $time)
    {
        //var_dump('recordBegin', $uri, $gets, $time);
    }

    /**
     * 记录投递的任务
     * @param string $key
     * @param float $time
     */
    public function recordEnd(string $key, float $time)
    {
        //var_dump('recordEnd', $key, $time);
    }
}
